package com.wallj.livechat;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by walljiang on 2016/6/27.
 */
public class AdapterMessage extends BaseAdapter {

    ArrayList<EntityMessage> datas = new ArrayList<>();
    Context mContext;
    String localIp;

    public ArrayList<EntityMessage> getDatas() {
        return datas;
    }

    public void addData(EntityMessage msg) {
        datas.add(msg);
    }

    public void addDatas(ArrayList<EntityMessage> msgs) {
        if (msgs != null) {
            for (EntityMessage msg : msgs) {
                datas.add(msg);
            }
        }
    }

    public AdapterMessage(Context context, String localIp) {
        this.mContext = context;
        this.localIp = localIp;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public EntityMessage getItem(int i) {
        return datas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Holder cache;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_message, null);
            cache = new Holder();
            cache.left = (TextView) view.findViewById(R.id.tv_message_left);
            cache.right = (TextView) view.findViewById(R.id.tv_message_right);
            view.setTag(R.id.tag_item_cache, cache);
        } else {
            cache = (Holder) view.getTag(R.id.tag_item_cache);
        }
        EntityMessage message = getItem(i);
        if (message.getAuthor().equals(localIp)) {
            cache.left.setVisibility(View.GONE);
            cache.right.setVisibility(View.VISIBLE);
            cache.right.setText(message.getMessage());
        } else {
            cache.left.setVisibility(View.VISIBLE);
            cache.right.setVisibility(View.GONE);
            cache.left.setText(message.getMessage());
        }
        return view;
    }

    class Holder {
        TextView left;
        TextView right;
    }
}
